package com.zwcl.glass.goods.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Sets;
import com.zwcl.common.core.utils.BeanUtils;
import com.zwcl.glass.goods.dto.SelectSkuDto;
import com.zwcl.glass.goods.dto.TagSpuDto;
import com.zwcl.glass.goods.entity.GoodsSku;
import com.zwcl.glass.goods.entity.GoodsSpu;
import com.zwcl.glass.goods.service.GoodsBaseService;
import com.zwcl.glass.goods.service.GoodsSkuService;
import com.zwcl.glass.goods.service.impl.GoodsPropertyServiceImpl;
import com.zwcl.glass.goods.service.impl.GoodsSkuServiceImpl;
import com.zwcl.glass.goods.vo.GoodsImagesVo;
import com.zwcl.glass.goods.vo.GoodsSummaryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xieyongping
 * @since 2021-01-13
 */
@RestController
@RequestMapping("/goodsSku")
public class GoodsSkuController {

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private GoodsSkuServiceImpl skuService;

    @GetMapping("/refreshCache")
    public void refreshCache(Integer spuId){
        skuService.deleteCache(GoodsBaseService.ZWCL_GLASS_GOODS_SKU_CACHE+"::"+spuId.toString());
        skuService.getSkusBySpuId(spuId);
    }

    //根据选择规格获取商品价格，和商品的库存
    //非常注意，sku中的properties字段，有可能顺序不一致
    @PostMapping("/get")
    public GoodsSku getSkuItem(@RequestBody SelectSkuDto dto)  {
        List<GoodsSku> skuList=goodsSkuService.getSkusBySpuId(dto.getSpuId());
        Map<Integer,GoodsSku> skuMap = skuList.stream().collect(Collectors.toMap(c -> c.getId(), c -> c));
        //从list中过滤出符合条件的单品
        Map<Integer,String> propertiesMap = skuList.stream().collect(Collectors.toMap(c -> c.getId(), c -> c.getProperties()));
        Integer skuId=null;
        for(Map.Entry<Integer,String> item : propertiesMap.entrySet()){
            if(matchProperties(item.getValue(),dto.getPropertySet())){
                skuId=item.getKey();
                break;
            }
        }
        return skuId==null ? null : skuMap.get(skuId);
    }

    /**
     * 属性匹配
     * @param dbProperties
     * @param dtoSet
     * @return
     */
    private Boolean matchProperties(String dbProperties,Set<String> dtoSet){
        Boolean succFlag = false;
        String[] propertyArr = dbProperties.split(",");
        //数据库的属性值，转化为set
        Set<String> dbSet =new HashSet<>();
        for (String item : propertyArr){
            if(!StringUtils.isBlank(item)){
                dbSet.add(item);
            }
        }
        //比较两个map，取差集
        Set differenceSet = Sets.difference(dbSet, dtoSet);
        if(differenceSet==null || differenceSet.size()==0)
            succFlag=true;
        return succFlag;
    }
}

